import model.student as stu
import model.util_conn as utl

class StudentDao(object):
    def save(self,stu):
         try:
            conn = utl.getConn()
            cursor = conn.cursor()
            sql = "insert into student(name,age,sex,grade) values('{}','{}','{}','{}')".format(stu.stu_name,stu.stu_age,stu.stu_sex,stu.stu_grade)
            cursor.execute(sql)
            conn.commit()
            print("保存成功")
         # except:
         #     print("发生异常")

         finally:
              cursor.close()
              conn.close()



    def delete(self,id):
        try:
            conn = utl.getConn()
            cursor = conn.cursor()
            sql = "delete from student where sid={}".format(id)
            cursor.execute(sql)
            conn.commit()
        except:
            print("发生异常")
        finally:
            cursor.close()
            conn.close()
            print("删除成功")

    def findByNameAndGrade(self,name,grade):
        try:
            conn = utl.getConn()
            cursor = conn.cursor()
            sql = "select * from student where name='{}' and grade='{}'".format(name,grade)
            cursor.execute(sql)
            stu = cursor.fetchone()
            return stu
        except:
            print("发生异常")

        finally:
            cursor.close()
            conn.close()

    def findAllStudent(self):
        try:
            conn = utl.getConn()
            cursor = conn.cursor()
            sql = "select * from student "
            cursor.execute(sql)
            data=cursor.fetchall()
            return data
        except:
            print("发生异常")

        finally:
            cursor.close()
            conn.close()

    def update(self,stu):
        try:
            conn = utl.getConn()
            cursor = conn.cursor()
            sql = "update  student set name='{}',age ={},sex='{}',grade='{}'where sid={}" \
                  "".format(stu.stu_name,stu.stu_age,stu.stu_sex,stu.stu_grade,stu.stu_id)
            cursor.execute(sql)
            conn.commit()
        except:
            print("发生异常")

        finally:
            cursor.close()
            conn.close()
    def findByID(self,id):
        try:
            conn = utl.getConn()
            cursor = conn.cursor()
            sql = "select * from student where sid={}".format(id)
            cursor.execute(sql)
            data=cursor.fetchone()
            conn.commit()
            return data
        except:
            print("发生异常")
        finally:
            cursor.close()
            conn.close()
